from goods.models import GoodsCategory, GoodsChannel
from .models import ContentCategory, Content
from django.template import loader
from django.conf import settings
import os
from meiduo_mall.utils.meiduo_channels import get_channels


def generate_index_html():
    # 1.查询：分类，广告
    categories = get_channels()

    # 1.2查询广告
    # contents={广告标识:[]}
    contents = {}
    content_categories = ContentCategory.objects.all()
    for category in content_categories:
        contents[category.key] = category.content_set.filter(status=True).order_by('sequence')

    # 2.渲染模板：生成html字符串
    context = {
        'categories': categories,
        'contents': contents
    }
    print(context)
    # 加载模型文件
    template = loader.get_template('index.html')
    # 渲染
    html_text = template.render(context)

    # 3.写文件：index.html
    with open(os.path.join(settings.GENERATE_STATIC_DIR, 'index.html'), 'w') as f:
        f.write(html_text)

    print('ok')
